package com.yunquan.ohana.ui.login

import android.app.Application
import android.text.InputType
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import cn.jpush.android.api.JPushInterface
import com.google.gson.Gson
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.entity.LoginEntity
import com.yunquan.ohana.entity.LoginV2Entity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.guide.GuideActivity
import com.yunquan.ohana.ui.main.MainActivity
import com.yunquan.ohana.utils.SPUtils
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import okhttp3.RequestBody.Companion.toRequestBody

class LoginViewModel(application: Application) : BaseViewModel(application) {

    val email = ObservableField<String>()
    val password = ObservableField<String>()
    val passwordType = ObservableField<Int>()
    val isShowPassword = ObservableField(false)

    val isEnter = ObservableField(false)

    val onShowPasswordClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val isShow = isShowPassword.get() ?: false
            isShowPassword.set(!isShow)
            if (!isShow) {
                passwordType.set(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)
            } else {
                passwordType.set(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
        }
    })

    val onForgetPasswordClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            sendPasswordResetEmail()
        }
    })

    val onLoginClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            login()
        }
    })


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        passwordType.set(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
    }

    private fun login() {
        if (StringUtils.isEmpty(email.get())) {
            ToastUtils.showShort(R.string.please_enter_your_email_address)
            return
        }
        if (StringUtils.isEmpty(password.get())) {
            ToastUtils.showShort(R.string.please_enter_your_password)
            return
        }
        val map = HashMap<String, Any>()
        map["email"] = email.get()!!
        map["password"] = password.get()!!
        val params = Gson().toJson(map)
        val body = params.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.appLogin(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<LoginV2Entity>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: LoginV2Entity?) {
                    super.onSuccess(result)
                    if (result != null) {
                        SPUtils.put("userId", result.userId!!)
                        SPUtils.put("token", result.token!!)
                        JPushInterface.setAlias(Utils.instance.context, 1, result.userId)
                        startActivity(MainActivity::class.java)
                        finish()
                    } else {
                        ToastUtils.showShort(Utils.instance.context.getString(R.string.account_not_tip))
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    if(e.code == -1){
                        ToastUtils.showShort(Utils.instance.context.getString(R.string.account_not_tip))
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    private fun sendPasswordResetEmail() {
        if (StringUtils.isEmpty(email.get())) {
            ToastUtils.showShort(R.string.please_enter_your_email_address)
            return
        }
        if (!StringUtils.isEmail(email.get())) {
            ToastUtils.showShort(R.string.only_accounts_bound_to_an_email_address_can_change_their_password)
            return
        }
        val map = HashMap<String, Any>()
        map["email"] = email.get()!!
        val params = Gson().toJson(map)
        val body = params.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.sendPasswordResetEmail(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        ToastUtils.showShort(R.string.the_email_was_sent_successfully)
                    } else {
                        ToastUtils.showShort(R.string.failed_email_delivery)
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    ToastUtils.showShort(R.string.error_in_email_delivery)
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}